/****************************************
 * 2018 - 2021 版权所有 CopyRight(c) 快程乐码信息科技有限公司所有, 未经授权，不得复制、转发
 */

package com.kclm.security03.config.security.login;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderNotFoundException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.Objects;

/******************
 * @Author yejf
 * @Version v1.0
 * @Create 2020-08-05 22:26
 * @Description 自定义认证管理器，通过它来管理认证提供者，也就是AuthenticationProvider
 */
@Component
@Slf4j
public class CusAuthenticationManager implements AuthenticationManager {

    @Autowired
    private AdminAuthenticationProvider adminAuthenticationProvider;

    public CusAuthenticationManager(AdminAuthenticationProvider adminAuthenticationProvider) {
        log.debug("创建 CusAuthenticationManager  对象实例...");
        this.adminAuthenticationProvider = adminAuthenticationProvider;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        log.debug("认证管理器通过调用认证提供者来认证");
        final Authentication result = this.adminAuthenticationProvider.authenticate(authentication);
        //判断认证的结果是否为null
        if(Objects.nonNull(result)) {
            return result;
        }
        //如果没有返回，则抛出异常
        throw new ProviderNotFoundException("Authentication failed!");
    }
}
